<template>
  <a-card title="分类" class="category-card">
    <template #extra>
      <a-button type="primary" @click="$emit('add')">
        <template #icon>
          <plus-outlined />
        </template>
        新建分类
      </a-button>
    </template>
    <draggable
      v-model="sortableCategories"
      :animation="200"
      item-key="key"
      handle=".category-drag-handle"
      :disabled="false"
      tag="div"
      class="category-list"
      :group="{ name: 'categories' }"
      ghost-class="ghost"
      chosen-class="chosen"
      drag-class="drag"
      :delay="50"
      :delayOnTouchOnly="true"
      :force-fallback="false"
      :animation-duration="200"
      :scroll="true"
      :scrollSensitivity="60"
      :scrollSpeed="20"
      @start="onDragStart"
      @end="onDragEnd"
      @choose="onDragChoose"
    >
      <template #item="{ element: category }">
        <div
          class="category-item"
          :class="{
            active: modelValue.includes(category.key),
            'is-dragging': loading,
            'no-drag': category.key === 'all'
          }"
          @click="handleSelect(category)"
          @contextmenu.prevent="showContextMenu($event, category)"
        >
          <div class="category-left">
            <holder-outlined class="category-drag-handle" />
            <folder-outlined class="category-icon" />
            <span class="category-label">{{ category.label }}</span>
          </div>
          <div class="category-actions" v-if="category.key !== 'all'" @click.stop>
            <edit-outlined class="action-icon" @click.stop="showEditModal(category)" />
            <delete-outlined class="action-icon" @click.stop="confirmDelete(category)" />
          </div>
        </div>
      </template>
    </draggable>
  </a-card>

  <a-dropdown :open="contextMenuVisible" :trigger="['contextmenu']" @openChange="handleContextMenuVisibleChange">
    <template #overlay>
      <a-menu>
        <a-menu-item key="export" @click="handleExport" v-if="selectedCategory?.key !== 'all'">
          <export-outlined />
          <span>导出分类</span>
        </a-menu-item>
        <a-menu-item key="import" @click="handleImport" v-if="selectedCategory?.key !== 'all'">
          <import-outlined />
          <span>导入到此分类</span>
        </a-menu-item>
      </a-menu>
    </template>
    <div
      class="context-menu-trigger"
      :style="{
        position: 'fixed',
        left: contextMenuPosition.x + 'px',
        top: contextMenuPosition.y + 'px'
      }"
    />
  </a-dropdown>

  <input type="file" ref="fileInput" style="display: none" accept=".json" @change="onFileSelected" />

  <a-modal v-model:open="editModalVisible" title="编辑分类" @ok="handleEditComplete" @cancel="cancelEdit" :confirmLoading="confirmLoading">
    <a-form :model="editForm">
      <a-form-item label="分类名称" name="label">
        <a-input v-model:value="editForm.label" placeholder="请输入分类名称" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { computed, ref } from 'vue'
import { PlusOutlined, DeleteOutlined, FolderOutlined, EditOutlined, ExportOutlined, ImportOutlined, HolderOutlined } from '@ant-design/icons-vue'
import { Modal, message } from 'ant-design-vue'
import draggable from 'vuedraggable'

const props = defineProps({
  categories: {
    type: Array,
    required: true
  },
  modelValue: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['add', 'update:modelValue', 'delete', 'edit', 'exportCategory', 'importCategory', 'sort'])

const displayCategories = computed(() => props.categories)

const editModalVisible = ref(false)
const confirmLoading = ref(false)
const editForm = ref({ key: '', label: '', id: null })

const showEditModal = (category) => {
  editForm.value = { ...category }
  editModalVisible.value = true
}

const handleEditComplete = () => {
  const newLabel = editForm.value.label.trim()
  if (newLabel && newLabel !== props.categories.find((c) => c.key === editForm.value.key)?.label) {
    confirmLoading.value = true
    try {
      emit('edit', {
        key: editForm.value.key,
        label: newLabel,
        id: editForm.value.id
      })
      editModalVisible.value = false
    } catch (error) {
      console.error('Error in handleEditComplete:', error)
    } finally {
      confirmLoading.value = false
    }
  }
}

const cancelEdit = () => {
  editModalVisible.value = false
  editForm.value = { key: '', label: '', id: null }
}

const confirmDelete = (category) => {
  Modal.confirm({
    title: '确定要删除这个分类吗？',
    content: '删除分类后，该分类下的书签将被移动到默认分类',
    onOk: () => {
      emit('delete', category)
    }
  })
}

const contextMenuVisible = ref(false)
const selectedCategory = ref(null)
const contextMenuPosition = ref({ x: 0, y: 0 })
const fileInput = ref(null)

const showContextMenu = (e, category) => {
  e.preventDefault()
  contextMenuPosition.value = { x: e.clientX, y: e.clientY }
  selectedCategory.value = category
  contextMenuVisible.value = true
}

const handleContextMenuVisibleChange = (visible) => {
  if (!visible) {
    contextMenuVisible.value = false
  }
}

const handleExport = () => {
  if (selectedCategory.value) {
    emit('exportCategory', selectedCategory.value)
    contextMenuVisible.value = false
  }
}

const handleImport = () => {
  if (selectedCategory.value) {
    fileInput.value?.click()
  }
}

const onFileSelected = (event) => {
  const file = event.target.files[0]
  if (file && selectedCategory.value) {
    emit('importCategory', { category: selectedCategory.value, file })
    event.target.value = ''
  }
  contextMenuVisible.value = false
}

const loading = ref(false)

// 排序相关
const sortableCategories = computed({
  get: () => props.categories,
  set: (value) => {
    const allCategory = value.find((c) => c.key === 'all')
    if (allCategory) {
      const otherCategories = value.filter((c) => c.key !== 'all')
      emit('sort', [allCategory, ...otherCategories])
    } else {
      emit('sort', value)
    }
  }
})

const onDragStart = () => {
  loading.value = true
}

const onDragEnd = () => {
  loading.value = false
}

const handleSelect = (category) => {
  emit('update:modelValue', [category.key])
  console.log(category.key)
}

const onDragChoose = (evt) => {
  // 阻止"全部"分类的拖拽
  if (evt.item.classList.contains('no-drag')) {
    evt.preventDefault()
  }
}
</script>

<style scoped>
.category-label {
  flex: 5 !important;
  font-size: 14px;
  transition: color 0.2s ease;
}
.category-card {
  height: 100%;
  overflow: hidden;
}

:deep(.ant-card-extra) {
  padding: 0;
}

:deep(.ant-btn) {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  height: 32px;
  padding: 4px 12px;
}

:deep(.anticon) {
  font-size: 14px;
}

:deep(.ant-card-body) {
  height: calc(100% - 57px);
  overflow-y: auto;
  padding: 12px !important;
}

:deep(.ant-menu) {
  border-inline-end: none !important;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-height: 100px;
}

.category-item {
  padding: 8px 2px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
  background: #fff;
  border: 1px solid transparent;
  user-select: none;
  position: relative;
  z-index: 1;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  gap: 8px;
}

.category-item.active {
  background: #e9ecef;
  border-color: #344767;
}

.category-item.active .category-icon,
.category-item.active .category-label {
  color: #344767;
}

.category-item:hover:not(.active) {
  background: #f5f5f5;
}

.category-left {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.category-item span {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.category-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}

.action-icon {
  font-size: 14px;
  color: #999;
  cursor: pointer;
  transition: color 0.3s;
  padding: 4px;
  border-radius: 4px;
  opacity: 0.6;
  transition: all 0.2s ease;
}

.action-icon:hover {
  color: #344767;
  background: rgba(24, 144, 255, 0.1);
  opacity: 1;
}

.action-icon.anticon-delete:hover {
  color: #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
}

.category-drag-handle {
  cursor: move;
  color: #999;
  padding: 4px;
  margin: -4px;
  border-radius: 4px;
  transition: opacity 0.2s ease, color 0.2s ease, background-color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.6;
  font-size: 16px;
}

.category-drag-handle:hover {
  opacity: 1;
}

.category-icon {
  color: #344767;
  flex-shrink: 0;
  font-size: 16px;
  transition: all 0.2s ease;
}

.ghost {
  opacity: 0.3;
  background: #f0f7ff;
  border: 1px dashed #344767;
  box-shadow: none !important;
  transform: scale(0.98);
}

.chosen {
  background: #fff;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  transform: scale(1.02);
  z-index: 10;
  border-color: #344767;
}

.drag {
  opacity: 1;
  background: #f0f7ff;
  border: 1px solid #344767;
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.15);
  transform: scale(1.02);
  z-index: 20;
}

.no-drag .category-drag-handle {
  cursor: not-allowed;
  opacity: 0.5;
}

.category-item.active .category-drag-handle {
  color: #344767;
  opacity: 0.8;
}

.category-item.active .action-icon {
  opacity: 0.8;
}
</style>
